<template>
  <div>
    <el-card class="box-card" style="margin-top: 30px" v-loading="loading">
      <el-form inline>
        <el-form-item>
          <el-input placeholder="用户名" v-model="searchParams.username" />
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search"
          >查询</el-button
        >
        <el-button type="default" @click="clearParams">清空</el-button>
      </el-form>

      <div style="margin: 20px 0">
        <el-button type="primary" @click="addUser"  v-if="$hasBP('btn.User.add')" >添 加</el-button>
        <el-button type="danger">批量删除</el-button>
      </div>

      <el-table :data="tableData.users" border stripe style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="nickName" label="用户昵称" />
        <el-table-column prop="roleName" label="角色列表" />
        <el-table-column prop="gmtCreate" label="创建时间" />
        <el-table-column prop="gmtModified" label="更新时间" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-user-solid"
              title="分配角色"
              @click="showAssignRole(row)"
              circle
            ></el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              title="修改用户"
              @click="updateUser(row)"
              circle
            ></el-button>
            <el-button
              type="success"
              size="small"
              icon="el-icon-delete"
              title="删除用户"
              @click="deleteUser(row.id)"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :page-size="searchParams.limit"
        :page-sizes="[3, 5, 7, 9]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="changeLimit"
        @current-change="changePage"
      />

      <el-dialog
        :title="userForm.id ? '修改用户' : '添加用户'"
        :visible.sync="isUserDialog"
        width="55%"
      >
        <el-form :model="userForm" label-width="120px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="userForm.nickName" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userForm.id">
            <el-input v-model="userForm.password" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="userEnter">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="isRoleDialog" width="55%">
        <el-form label-width="100px">
          <el-form-item label="用户名">
            <el-input disabled v-model="username" />
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              :indeterminate="roleForm.isIndeterminate"
              v-model="roleForm.checkAll"
              @change="changeAllChecked"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="roleForm.userRoleIds"
              @change="changeChecked"
            >
              <el-checkbox
                v-for="item in roleForm.allRoles"
                :key="item.id"
                :label="item.id"
                >{{ item.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="roleEnter">保 存 </el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  assignUserRoleListApi,
  getUserListApi,
  getUserRoleListApi,
  removeUserApi,
  saveOrUpdateUserApi,
} from "@/api/acl/user";
export default {
  data() {
    return {
      // 表单的数据
      tableData: {
        users: [], // 所有用户信息
        selectedIds: [], //  可能是选中状态??
      },
      // 搜索用到的参数
      searchParams: {
        page: 1, // 当前页面
        limit: 5, // 每页数量
        username: "", //
        searchUsername: "",
      },
      total: 0, // 总数量
      loading: false, // 列表正在加载中
      isRoleDialog: false, // 角色相关  弹窗
      isUserDialog: false, // 用户相关  弹窗
      // 新增或修改的用户信息
      userForm: {
        username: "",
        nickName: "",
        password: "",
      },
      // 这两个变量是操作角色时用到的
      userId: "", // 用户id
      username: "", //
      // 角色信息
      roleForm: {
        userRoleIds: [], // 所选角色的id
        allRoles: [], // 角色列表
        checkAll: false,
        isIndeterminate: false,
      },
    };
  },
  methods: {
    // 方法1 封装获取用户列表的方法
    async getUserList() {
      this.loading = true;
      const page = this.searchParams.page;
      const limit = this.searchParams.limit;
      const res = await getUserListApi(page, limit, {
        username: this.searchParams.searchUsername,
      });
      this.tableData.users = res.data.items;
      this.total = res.data.total;
      this.loading = false;
    },
    // 方法2 改变当前页码
    changePage(newPage) {
      this.searchParams.page = newPage;
      this.getUserList();
    },
    // 方法3 改变每页数量
    changeLimit(newLimit) {
      this.searchParams.limit = newLimit;
      this.getUserList();
    },

    // 方法 搜索
    search() {
      this.searchParams.searchUsername = this.searchParams.username;
      this.getUserList(1);
    },

    // 清空搜索框
    clearParams() {
      this.searchParams.username = "";
      this.searchParams.searchUsername = "";
      this.getUserList(1);
    },

    // 方法 添加用户
    addUser() {
      this.userForm = {
        username: "",
        nickName: "",
        password: "",
      };
      this.isUserDialog = true;
    },

    // 方法  修改用户
    updateUser(data) {
      // 系统数据不能修改
      this.userForm = { ...data };
      this.isUserDialog = true;
    },

    // 方法  删除用户
    async deleteUser(id) {
      const res = await removeUserApi(id);
      this.$message.success("删除" + res.message);
      this.getUserList();
    },

    // 方法 用户弹窗确定事件
    async userEnter() {
      const user = this.userForm;
      if (user.username === "admin") {
        alert("admin账号不能添加或更新");
        return;
      }
      try {
        const res = await saveOrUpdateUserApi(user);
        this.isUserDialog = false;
        this.$message.success("添加或修改成功");
        this.getUserList();
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 方法 分配角色
    showAssignRole(data) {
      this.isRoleDialog = true;
      // 调用获取角色列表方法
      this.getRolesList(data.id);
      this.userId = data.id;
      this.username = data.username;
    },

    // 方法 封装获取角色列表的 方法
    async getRolesList(id) {
      const res = await getUserRoleListApi(id);
      const { allRolesList, assignRoles } = res.data;
      this.roleForm.allRoles = allRolesList;
      this.roleForm.userRoleIds = assignRoles.map((item) => item.id);
      this.roleForm.checkAll = allRolesList.length === assignRoles.length;
      // Checkbox 多选框 的 indeterminate 属性表示 多选框的不确定状态
      this.roleForm.isIndeterminate =
        assignRoles.length > 0 && assignRoles.length < allRolesList.length;
    },

    // 方法 点击小选框方法
    changeChecked() {
      const { userRoleIds, allRoles } = this.roleForm;
      this.roleForm.checkAll = allRoles.length === userRoleIds.length;
      this.roleForm.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length;
    },

    // 方法 点击全选框
    changeAllChecked(checked) {
      // checked是全选框的状态 true 或 false  根据值判断 选中角色有什么
      this.roleForm.userRoleIds = checked
        ? this.roleForm.allRoles.map((item) => item.id)
        : [];
      // 不是true和false 那么就是不确定状态
      this.roleForm.isIndeterminate = false;
    },

    // 方法 分配角色确定事件
    async roleEnter() {
      const roleIds = this.roleForm.userRoleIds.join(",");
      await assignUserRoleListApi(this.userId, roleIds);
      this.isRoleDialog = false;
      this.getUserList();
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style>
.el-pagination {
  margin-top: 20px;
}
</style>
